package svc

import (
	"fmt"
	"github.com/zachary/tbox/internal/web/util"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"runtime/debug"
)

func errorHandler(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				logx.Error(fmt.Sprintf("%v\n%s", err, debug.Stack()))
				switch e := err.(type) {
				case error:
					httpx.Error(w, util.Error(e))
				case string:
					httpx.Error(w, util.Fail(e))
				default:
					httpx.Error(w, util.Fail(fmt.Sprint(e)))
				}
			}
		}()
		next(w, r)
	}
}

func AddMiddleware(server *rest.Server) {
	logx.Infof("Initializing middleware ...")
	server.Use(errorHandler)
	logx.Infof("Initialized middleware.")
}
